package org.ilovecode.display {
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	import gs.TweenLite;
	import gs.easing.*;
	
	import org.ilovecode.Utilities;
	import org.ilovecode.config.Definitions;
	import org.ilovecode.events.ApartmentEvent;
	import org.ilovecode.events.MenuEvent;
	import org.ilovecode.screen.Screen;
	import org.ilovecode.screen.ScreenGroup;
	import org.ilovecode.screen.ScreenName;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class ApartmentLayout extends Screen {
		
		public var apartmentLayoutGraphic:MovieClip;
		public var apartmentLayoutInfo:ApartmentLayoutInfoWindow;
		public var apartmentZoom:SimpleButton;
		public var backButton:SimpleButton;
		public var backTextField:TextField;
		public var infoTextField:TextField;
		public var statusTextField:TextField;
		public var downloadPDFButton:SimpleButton;
		public var compas:MovieClip;
		public var progressBar:MovieClip;
		
		private var roomID:int = -1;
		private var floorID:int = -1;
		private var _source:String = "";
		private var apartment:Apartment;
		private var image:DisplayObject = null;
		private var thumb:DisplayObject = null;
		private var isBusiness:Boolean = false;
		
		private var floorTexts:Array = new Array(
			"TLOCRT PRIZEMLJA",
			"TLOCRT PRVOG KATA",
			"TLOCRT DRUGOG KATA",
			"TLOCRT TREĆEG KATA",
			"TLOCRT ČETVRTOG KATA",
			"TLOCRT PETOG KATA",
			"TLOCRT ŠESTOG KATA",
			"TLOCRT SEDMOG KATA",
			"TLOCRT OSMOG KATA");
		
		public function ApartmentLayout(roomID:int, floorID:int, source:String, isBusiness:Boolean = false) {
			super(ScreenName.APARTMENT_LAYOUT, ScreenGroup.APARTMENTS, "apartmentLayout");
			
			this.roomID = roomID;
			this.floorID = floorID;
			this._source = source;
			this.isBusiness = isBusiness;
		}
		
		override protected function initText():void
		{
			super.initText();
			
			if (source == "search") {
				backTextField.text = "PRETRAŽIVANJE";
			} else {
				backTextField.text = String(floorTexts[floorID]);
			}
		}
		
		override protected function initUI():void
		{
			super.initUI();
			
			showProgressBar();
			var url:String = "http://www.centar-bundek.hr/xml/Apartment/" + roomID;
			Utilities.loadURL(url, loadDetailsComplete);
		}
		
		
		override protected function addListeners():void
		{
			super.addListeners();
			
			backButton.addEventListener(MouseEvent.CLICK, handle_Click);
			downloadPDFButton.addEventListener(MouseEvent.CLICK, handle_Click);
			apartmentZoom.addEventListener(MouseEvent.CLICK, handle_Click);
		}
		
		override protected function removeListeners():void
		{
			super.removeListeners();
			
			backButton.removeEventListener(MouseEvent.CLICK, handle_Click);
			downloadPDFButton.removeEventListener(MouseEvent.CLICK, handle_Click);
			apartmentZoom.removeEventListener(MouseEvent.CLICK, handle_Click);
		}
		
		
		private function handle_Click(event:MouseEvent):void
		{
			switch(event.target)
			{
				case backButton:
					if (source == "floorLayout") {
						controller.showFloor(floorID);
					} else if (source == "floorLayoutBusinessSelling") {
						controller.showScreen(ScreenName.LAYOUT_SHOP);
					} else if (source == "search") {
						controller.showScreen(ScreenName.SEARCH);
					} else {
						throw new Error("Illegal source for apartments");
					}
					//this.dispatchEvent(new MenuEvent(MenuEvent.PREVIOUS, String(floorID)));
					break;
				case downloadPDFButton:
					var url:String = "http://www.centar-bundek.hr/Content/PDF/" + apartment.building + "_" + apartment.name + ".pdf";
					navigateToURL(new URLRequest(url), "_blank");
					break;
				case apartmentZoom:
					//this.dispatchEvent(new ApartmentEvent(ApartmentEvent.CLICK, image));
					controller.showImage(image);
					break;
				default:
					break;
			}
		}
		
		/*public function init(roomID:int, floorID:int, source:String, isBusiness:Boolean = false):void {
			this.roomID = roomID;
			this.floorID = floorID;
			this._source = source;
			this.isBusiness = isBusiness;
			
			if (source == "search") {
				backTextField.text = "PRETRAŽIVANJE";
			} else {
				backTextField.text = String(floorTexts[floorID]);
			}
			initListeners();
			loadDetails();
		}
		
		private function initListeners():void {
			backButton.addEventListener(MouseEvent.CLICK, backButtonClick);
			downloadPDFButton.addEventListener(MouseEvent.CLICK, downloadPDFButtonClick);
			apartmentZoom.addEventListener(MouseEvent.CLICK, apartmentZoomClick);
		}
		
		private function backButtonClick(event:MouseEvent):void {
			this.dispatchEvent(new MenuEvent(MenuEvent.PREVIOUS, String(floorID)));
		}
		
		private function downloadPDFButtonClick(event:MouseEvent):void {
			var url:String = "http://www.centar-bundek.hr/Content/PDF/" + apartment.building + "_" + apartment.name + ".pdf";
			navigateToURL(new URLRequest(url), "_blank");
		}
		
		private function apartmentZoomClick(event:MouseEvent):void {
			this.dispatchEvent(new ApartmentEvent(ApartmentEvent.CLICK, image));
		}
		
		private function loadDetails():void {
			showProgressBar();
			var url:String = "http://www.centar-bundek.hr/xml/Apartment/" + roomID;
			Utilities.loadURL(url, loadDetailsComplete);
		}*/
		
		private function loadDetailsComplete(event:Event):void {
			var xml:XML = XML(event.target.data);
			
			if (xml.children().length() > 0) {
				var id:int = int(xml.id);
				var code:String = String(xml.code);
				var building:String = String(xml.building);
				var state:String = String(xml.state);
				var floor:String = String(xml.floor);
				var numRooms:String = String(xml.roomsnumber);
				var area:Number = Number(xml.area);
				var roomList:Array = new Array();
				if (!isBusiness) {
					for each(var room:XML in xml.rooms.children()) {
						var o:Object = new Object();
						o.name = room.type;
						o.area = Number(room.area).toFixed(2);
						roomList.push(o);
					}
				}
				var graphics:XML = XML(xml.graphics);
				var thumbURL:String = "http://" + String(graphics.flrlayout);
				
				var index:int = thumbURL.lastIndexOf("/");
				var imageURL:String = thumbURL.slice(0, index) + "/zoom" + thumbURL.slice(index);
				
				Utilities.loadContent(thumbURL, thumbLoaded);
				Utilities.loadContent(imageURL, imageLoaded);
				apartment = new Apartment(id, code, building, state, floor, numRooms, area, roomList, thumbURL, imageURL);
				if (!isBusiness) {
					apartmentLayoutInfo.init(apartment);
				}
				
				var name:String = (isBusiness) ? "PROSTOR" : "STAN";
				infoTextField.text = name + " " + apartment.building + "-" + apartment.name + " - " + apartment.floor + " - " + apartment.numRooms + " - " + apartment.area + " m2";
				if (isBusiness && state == "stan za prodaju") {
					statusTextField.text = "PROSTOR ZA PRODAJU";
				} else {
					statusTextField.text = state.toLocaleUpperCase();
				}
				
				var color:uint = 0;
				switch(state) {
					case "stan za prodaju":
						color = Definitions.FOR_SALE_COLOR;
						break;
					case "prodano":
						color = Definitions.SOLD_COLOR;
						break;
					case "rezervirano":
						color = Definitions.RESERVED_COLOR;
						break;
				}
				var tf:TextFormat = new TextFormat();
				tf.color = color;
				statusTextField.setTextFormat(tf);
				
			} else {
				throw new Error("Error reading apartment from database");
			}
		}
		
		private function thumbLoaded(event:Event):void {
			var defaultWidth:Number = 357;
			var defaultHeight:Number = 293;
			
			var loader:Loader = Loader(event.currentTarget.loader);
			var content:DisplayObject = loader.content;
			content.x = (defaultWidth - content.width) / 2;
			content.y = (defaultHeight - content.height) / 2;
			thumb = content;
			
			apartmentLayoutGraphic.addChild(content);
			
			if (isBusiness) {
				apartmentLayoutGraphic.x = (this.width - apartmentLayoutGraphic.width) / 2;
				apartmentLayoutGraphic.y = (this.height - apartmentLayoutGraphic.height) / 2 + 50;
			}
			
			//compas.x = apartmentLayoutGraphic.x + content.x + content.width;
			//compas.y = apartmentLayoutGraphic.y + content.y + content.height;
			
			//If image is loaded, thumb is loaded, so is xml, so hide progress bar
			if (image != null) {
				hideProgressBar();
			}
		}
		
		private function imageLoaded(event:Event):void {
			var loader:Loader = Loader(event.currentTarget.loader);
			image = loader.content;
			
			//If thumb is loaded, image is loaded, so is xml, so hide progress bar
			if (thumb != null) {
				hideProgressBar();
			}
		}
		
		private function show():void {
			TweenLite.from(apartmentLayoutGraphic, 0.5, { x: apartmentLayoutGraphic.x+100, alpha:0 } );
			TweenLite.from(apartmentLayoutInfo, 1, { y: apartmentLayoutInfo.y+100, alpha:0 } );
		}
		
		private function showProgressBar():void {
			progressBar.gotoAndPlay(0);
			apartmentLayoutInfo.visible = false;
			apartmentLayoutGraphic.visible = false;
			apartmentZoom.visible = false;
			compas.visible = false;
		}
		
		private function hideProgressBar():void {
			progressBar.visible = false;
			if (!isBusiness) {
				apartmentLayoutInfo.visible = true;
			}
			apartmentLayoutGraphic.visible = true;
			apartmentZoom.visible = true;
			compas.visible = true;
			show();
		}
		
		public function get source():String {
			return _source;
		}
		
	}

}